# -*- coding: UTF-8 -*-

import datetime
import json
import logging
import os
import re
import smtplib
# 负责构造图片
from email.mime.image import MIMEImage
# 负责将多个对象集合起来
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from time import sleep

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

# # 校园网用户名密码
# username = '用户名'
# password = '密码'

# # qq邮箱
# email = 'QQ邮箱'
# # qq邮箱里面设置
# auth = '授权码'

def sentemail(str, pic_file, sender, auth, receiver):
    host = 'smtp.' + re.findall(r".*@(.*)", sender)[0]
    port = 465
    # 去qq生成授权码
    pwd = auth
    
    msg = MIMEMultipart('related')
    msg['subject'] = datetime.datetime.now().strftime('%y%m%d') + '厦大健康打卡'
    msg['from'] = sender
    msg['to'] = receiver

    text = str
    bodycontent = f'''
    <h2> <p style="color:red">{text}</p> </h2>
    '''
    
    with open(pic_file,'rb') as image:
        image_info = MIMEImage(image.read())
        image_info.add_header('Content-Id',f'<image1>')
        msg.attach(image_info)
    html = """
    <p> 网页截图：
        <br><img src="cid:image1"></br>
    </p>
    """
    msg.attach(MIMEText(bodycontent + html, "html", "utf-8"))
    try:
        s = smtplib.SMTP_SSL(host, port, timeout = 100)
        s.login(sender, pwd)
        s.sendmail(sender, receiver, msg.as_string())
        # mylog.info("发送邮件成功")
        print("发送邮件成功")
    except smtplib.SMTPException:
        # mylog.error("发送邮件失败")
        print("发送邮件失败")



def del_files(path):
    for root, dirs, file in os.walk(path):
        for name in file:
            if name.endswith(".png"):
                os.remove(os.path.join(root, name))


if __name__ == '__main__':

    json_data = []
    with open('./config.json', 'r', encoding='utf8') as fp:
        json_data = json.load(fp)
        fp.close()

    username = json_data['username']
    password = json_data['password']
    sender = json_data['sender']
    auth = json_data['auth']
    recevier = json_data['receiver']

    if not os.path.exists('./logs/'):
        os.makedirs('./logs')
    if not os.path.exists('./logs/log_test.txt'):
        file = open('./logs/log_test.txt', 'w')
        file.write('')
    if not os.path.exists('./pic/'):
        os.makedirs('./pic')
    mylog = logging.getLogger('mylogger')
    mylog.setLevel(logging.INFO)

    # 处理器

    handler = logging.FileHandler('./logs/log_test.txt')
    handler.setLevel(logging.DEBUG)
    # 格式器
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    handler.setFormatter(formatter)

    mylog.addHandler(handler)

    # 不显示浏览器
    desired_capabilities = DesiredCapabilities.EDGE
    desired_capabilities["pageLoadStrategy"] = "none"
        
    driver = webdriver.Edge("./msedgedriver.exe")
    # option = webdriver.ChromeOptions()
    # option.add_argument("headless")
    # 通过  edge://version/ 查看浏览器版本
    # https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/ 下载对应版本插件
    # 解压填入路径
    # driver = webdriver.Chrome("./chromedriver.exe", chrome_options=option)

    # 打卡网站
    # 最大化界面
    # driver.maximize_window()
    driver.get('https://xmuxg.xmu.edu.cn/app/214')
    driver.implicitly_wait(40)
    # 统一身份认证按钮
    driver.find_elements_by_class_name("primary-btn")[2].click()
    sleep(2)
    # 用户密码登录
    driver.find_element_by_id("username").clear()
    driver.find_element_by_id("password").clear()
    driver.find_element_by_id("username").send_keys(username)
    driver.find_element_by_id("password").send_keys(password)
    # 点击登录
    driver.find_element_by_class_name("auth_login_btn").click()
    sleep(5)
    # 这里修改了原作者的语句，把网址变了，在获取了cookie之后刷新一遍即可
    # driver.find_elements_by_class_name("app_child")[2].click()
    # 跳转到新网页
    driver.switch_to.window(driver.window_handles[-1])
    driver.get('https://xmuxg.xmu.edu.cn/app/214')
    driver.implicitly_wait(40)
    # 停止一下，不然太快
    sleep(5)
    # 点击我的表单
    driver.find_elements_by_class_name("tab")[1].click()
    sleep(3)
    # 判断是否已经打卡
    text = driver.find_element_by_xpath("//div[@data-name='select_1582538939790']").text
    if('Yes' in text):
        driver.find_element_by_xpath("//button[contains(.,'日志')]").click()
        sleep(3)
        snipname = './pic/' + datetime.datetime.now().strftime('%y%m%d%H%M%S') + '.png'
        driver.get_screenshot_as_file(snipname)
        sentemail('今日已经打卡', snipname, sender, auth, recevier)
        # sentemail("今日已经打卡")
        mylog.info("今日已经打卡")
    # 211030更新，更新了是否激活医保凭证，大概率以后会撤销，且尚不清楚之后需要每日确认还是只需要确认一次,下段先做注释
    # else:
    #     # vue和传统下拉框不一样
    #     driver.find_element_by_css_selector("[data-name='select_1582538939790']").click()
    #     sleep(3)
    #     driver.find_element_by_css_selector("[title='是 Yes'][class='btn-block']").click()
    #     # 点击保存
    #     driver.find_element_by_class_name("form-save").click()
    #     sleep(3)
    #     # 点击弹出框确定
    #     driver.switch_to.alert.accept()
    #     sleep(5)
    #     driver.refresh()
    #     sleep(5)
    #     # 点击我的表单
    #     driver.find_elements_by_class_name("tab")[1].click()
    #     sleep(3)
    #     driver.find_element_by_xpath("//button[contains(.,'日志')]").click()
    #     sleep(3)
    #     snipname = './pic/' + datetime.datetime.now().strftime('%y%m%d%H%M%S') + '.png'
    #     driver.get_screenshot_as_file(snipname)
    #     sentemail('打卡成功', snipname, sender, auth, recevier)
    #     mylog.info("打卡成功")
    elif 'Yes' not in driver.find_element_by_xpath("//div[@data-name='select_1635333230224']").text:
        driver.find_element_by_css_selector("[data-name='select_1635333230224']").click()
        sleep(3)
        driver.find_element_by_css_selector("[title='是Yes'][class='btn-block']").click()
        sleep(3)
        driver.find_element_by_css_selector("[data-name='select_1582538939790']").click()
        sleep(3)
        driver.find_element_by_css_selector("[title='是 Yes'][class='btn-block']").click()
        # 点击保存
        driver.find_element_by_class_name("form-save").click()
        sleep(3)
        # 点击弹出框确定
        driver.switch_to.alert.accept()
        sleep(5)
        driver.refresh()
        sleep(5)
        # 点击我的表单
        driver.find_elements_by_class_name("tab")[1].click()
        sleep(3)
        driver.find_element_by_xpath("//button[contains(.,'日志')]").click()
        sleep(3)
        snipname = './pic/' + datetime.datetime.now().strftime('%y%m%d%H%M%S') + '.png'
        driver.get_screenshot_as_file(snipname)
        sentemail('打卡成功', snipname, sender, auth, recevier)
        mylog.info("打卡成功")
    else:
        # vue和传统下拉框不一样
        driver.find_element_by_css_selector("[data-name='select_1582538939790']").click()
        sleep(3)
        driver.find_element_by_css_selector("[title='是 Yes'][class='btn-block']").click()
        # 点击保存
        driver.find_element_by_class_name("form-save").click()
        sleep(3)
        # 点击弹出框确定
        driver.switch_to.alert.accept()
        sleep(5)
        driver.refresh()
        sleep(5)
        # 点击我的表单
        driver.find_elements_by_class_name("tab")[1].click()
        sleep(3)
        driver.find_element_by_xpath("//button[contains(.,'日志')]").click()
        sleep(3)
        snipname = './pic/' + datetime.datetime.now().strftime('%y%m%d%H%M%S') + '.png'
        driver.get_screenshot_as_file(snipname)
        sentemail('打卡成功', snipname, sender, auth, recevier)
        mylog.info("打卡成功")

    sleep(1)
    # 采用close()执行脚本的时候不会自动退出
    del_files("./pic/")
    driver.quit()
